"""
@author: Jamiexu/Jamie793
@version: 1.0
@date: 2020/10/4
@time: 12:20
@mail: doxm@foxmail.com
@blog: https://blog.jamiexu.cn
"""
import json
import os

import requests

HTTP_PROXY = {
    "https": "127.0.0.1:10809"
}

VIDEO_HEIGHT = (1080, 720, 480, 360)

DOWNLOAD_PAHT = "C:\\Users\\Jamiexu\\Desktop\\Video"


def getYTInitialData(url):
    body = requests.get(url, proxies=HTTP_PROXY).text
    data = body[body.find('window["ytInitialData"] = ') + len('window["ytInitialData"] = '):body.find(
        ''';
    window["ytInitialPlayerResponse"] ''')]
    jsonData = json.loads(data)['contents']['twoColumnWatchNextResults']['playlist']['playlist']['contents']
    datas = []
    for i in jsonData:
        # print(i['playlistPanelVideoRenderer']['videoId'])
        id = i['playlistPanelVideoRenderer']['videoId']
        title = i['playlistPanelVideoRenderer']['title']['simpleText']
        datas.append({
            'id': id,
            'title': title
        })
    return datas


def getVideoAbsPath(id):
    body = requests.get("https://www.youtube.com/watch?v=" + id).text
    data = body[body.find('''ytplayer.config = ''') + len('''ytplayer.config = '''):
                body.find(''';ytplayer.web_player_context_config''')]
    # data = data[data.find('"player_response":"')+len('"player_response":"'):]
    player_response = json.loads(data)['args']['player_response']
    # unicode_escape
    player_response = player_response.encode('utf-8').decode('utf-8')
    jsonData = json.loads(player_response)['streamingData']['formats']

    for i in jsonData:
        for j in VIDEO_HEIGHT:
            if j == i['height']:
                return i['url'].encode('utf-8').decode('unicode_escape')


def downloadV(name, url):
    req = requests.get(url, proxies=HTTP_PROXY)
    with open(DOWNLOAD_PAHT + '\\' + name + '.mp4', 'wb') as f:
        f.write(req.content)
        f.flush()
        f.close()


if __name__ == '__main__':
    if not os.path.exists(DOWNLOAD_PAHT):
        os.mkdir(DOWNLOAD_PAHT)
    datas = getYTInitialData(
        "https://www.youtube.com/watch?v=n4yhA8tIs_g&list=PLEoXcZ9ksJKiazW1oBVyNX3RANl2t6lUD&index=42")
    for i in datas:
        url = getVideoAbsPath(i['id'])
        print(url)
        downloadV(i['title'], url)
